package com.siyuanren.gcocp.service.impl;

import cn.hutool.core.date.DateUtil;
import com.siyuanren.gcocp.dto.TemplateMsgDTO;
import com.siyuanren.gcocp.entity.*;
import com.siyuanren.gcocp.factory.WxTemplateMsgFac;
import com.siyuanren.gcocp.mapper.MyTaskMapper;
import com.siyuanren.gcocp.mapper.base.WxUserTimerTaskMapper;
import com.siyuanren.gcocp.service.TaskService;
import com.siyuanren.gcocp.service.MsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by   anxing
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.service.impl
 * Date         2018/6/21
 * Time         15:59
 * Description
 */
@Slf4j
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    MyTaskMapper taskMapper;
    @Autowired
    WxUserTimerTaskMapper timerTaskMapper;
    @Autowired
    MsgService msgService;

    @Override
    public void studyMorningRemind() {
        List<WxUser> userList = taskMapper.getUserNeedToStudy();
        for (WxUser wxUser : userList) {
            List<WxCourse> courses = taskMapper.getStudingCourse(wxUser.getId());
            WxTemplateMsg msg = WxTemplateMsgFac.getStudyMorningRemindMsg(getCourseName(courses));
            msgService.sendTemplateMessage(wxUser.getOpenid(), msg);
        }
    }
    @Override
    public void studyEveningRemind() {
        List<WxUser> userList = taskMapper.getUserNeedToStudy();
        for (WxUser wxUser : userList) {
            List<WxCourse> courses = taskMapper.getStudingCourse(wxUser.getId());
            WxTemplateMsg msg = WxTemplateMsgFac.getStudyEventingRemindMsg(getCourseName(courses));
            msgService.sendTemplateMessage(wxUser.getOpenid(), msg);
        }
    }

    @Override
    public void sendTemplateMsg(int sendTime) {
        List<TemplateMsgDTO> mgsList = taskMapper.getTemplateMsg(sendTime);

        for (TemplateMsgDTO templateMsgDTO : mgsList) {
            msgService.sendTemplateMessage(templateMsgDTO.getUserOpenId(), templateMsgDTO);
            setHasBeenSendToday(templateMsgDTO.getTaskId());
        }
    }


    public String getCourseName(List<WxCourse> courses) {
        if (courses == null || courses.isEmpty()) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (WxCourse cours : courses) {
            sb.append(cours.getCourseName()).append(",");
        }
        return sb.substring(0, sb.length() -2);
    }

    /**
     * 设置消息当天已发送
     * @param taskId
     */
    public void setHasBeenSendToday(Integer taskId) {
        WxUserTimerTask record = timerTaskMapper.selectByPrimaryKey(taskId);
        record.setLastSendDate(new Date());
        timerTaskMapper.updateByPrimaryKeySelective(record);
    }
}
